package com.cskaoyan.service;

import com.cskaoyan.bean.bo.*;
import com.cskaoyan.bean.entity.*;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.utils.LimitListSizeUtil;
import com.cskaoyan.utils.ad.Ban;

import com.cskaoyan.utils.ad.TransUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *后台
 *@Author : Patrick 田赫
 *@Software : IntelliJ IDEA
 * @Time 2021-10-18
 */
@Transactional
@Service
public class PromotionServiceImpl implements PromotionService {
    @Autowired
    AdMapper adMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    CouponUserMapper couponUserMapper;

    @Autowired
    TopicMapper topicMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    Ban ban;

    @Override
    public BasePageData getAdList(String name, String content, BaseParamBo paramBo) {

        BasePageData pageData = new BasePageData();
        //分页插件
        PageHelper.startPage(paramBo.getPage(),paramBo.getLimit());
        //Example构造条件
        AdExample adExample = new AdExample();
        //排序
        adExample.getOrderByClause(paramBo.getSort() + " " + paramBo.getOrder());
        //创建Criteria
        AdExample.Criteria criteria = adExample.createCriteria();
        //调用example方法
        if(name != null && !"".equals(name)){
            criteria.andNameLike("%" + name + "%");
        }
        if(content != null && !"".equals(content)){
            criteria.andContentLike("%" + content + "%");
        }
        criteria.andDeletedEqualTo(false);
        //查询
        List<Ad> adList = adMapper.selectByExample(adExample);
        List<AdItems> adItemsList = new ArrayList<>();
        for(Ad ad : adList){
            //通过工具类将pojo变成vo
            adItemsList.add(TransUtils.Ad2Vo(ad));
        }
        //获取total
        PageInfo<Ad> pageInfo = new PageInfo<>(adList);
        int total = (int) pageInfo.getTotal();
        pageData.setTotal(total);
        pageData.setPage(pageInfo.getPageNum());
        pageData.setLimit(pageInfo.getPageSize());
        pageData.setPages(pageInfo.getPages());
        pageData.setList(adItemsList);
        return pageData;
    }

    @Override
    public void deleteAd(AdBo adBo) {
        Ad ad = TransUtils.Bo2Ad(adBo);
        ad.setDeleted(true);
        adMapper.updateByPrimaryKey(ad);
    }

    @Override
    public BasePageData getCuList(String name, Short type, Short status, BaseParamBo paramBo) {
        BasePageData basePageData = new BasePageData();
        PageHelper.startPage(paramBo.getPage(),paramBo.getLimit());
        CouponExample couponExample = new CouponExample();
        couponExample.getOrderByClause(paramBo.getSort() + " " + paramBo.getOrder());
        CouponExample.Criteria criteria = couponExample.createCriteria();
        if(name != null && !"".equals(name)){
            criteria.andNameLike("%" + name + "%");
        }
        if(type != null && !"".equals(type)){
            criteria.andTypeEqualTo(type);
        }
        if(status != null && !"".equals(status)){
            criteria.andStatusEqualTo(status);
        }
        criteria.andDeletedEqualTo(false);
        List<Coupon> couponList = couponMapper.selectByExample(couponExample);
        List<CuItems> cuItemsList = new ArrayList<>();
        for(Coupon coupon : couponList){
            cuItemsList.add(TransUtils.Coupon2CouponVo(coupon));
        }
        PageInfo<Coupon> pageInfo = new PageInfo<>(couponList);
        int total = (int) pageInfo.getTotal();
        basePageData.setTotal(total);
        basePageData.setPages(pageInfo.getPages());
        basePageData.setLimit(pageInfo.getPageSize());
        basePageData.setPage(pageInfo.getPageNum());
        basePageData.setList(cuItemsList);
        return basePageData;
    }

    @Override
    public void deleteCu(CouponBo couponBo) {
        Coupon coupon = TransUtils.CouponBo2Coupon(couponBo,couponMapper);
        coupon.setDeleted(true);
        couponMapper.updateByPrimaryKey(coupon);
    }

    @Override
    public CouponVo getCuById(Integer id) {
        Coupon coupon = couponMapper.selectByPrimaryKey(id);
        CouponVo couponVo = TransUtils.CouponToCouponVo(coupon);
        return couponVo;
    }

    @Override
    public BasePageData getListUser(Integer couponId, Integer userId, Short status, BaseParamBo paramBo) {
        BasePageData pageData = new BasePageData();
        PageHelper.startPage(paramBo.getPage(),paramBo.getLimit());
        CouponUserExample couponUserExample = new CouponUserExample();
        couponUserExample.getOrderByClause(paramBo.getSort() + " " + paramBo.getOrder());
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andCouponIdEqualTo(couponId);
        if(userId != null && !"".equals(userId)){
            criteria.andUserIdEqualTo(userId);
        }
        if(status != null && !"".equals(status)){
            criteria.andStatusEqualTo(status);
        }
        criteria.andDeletedEqualTo(false);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        List<CouponUserVo> couponUserVos = new ArrayList<>();
        for(CouponUser couponUser : couponUsers){
            couponUserVos.add(TransUtils.CouponUser2CouponUserVo(couponUser));
        }
        PageInfo<CouponUser> pageInfo = new PageInfo<>(couponUsers);
        pageData.setList(couponUserVos);
        int total = (int) pageInfo.getTotal();
        pageData.setTotal(total);
        pageData.setPage(pageInfo.getPageNum());
        pageData.setLimit(pageInfo.getPageSize());
        pageData.setPages(pageInfo.getPages());
        return pageData;
    }

    @Override
    public BasePageData getTopics(String title, String subtitle,BaseParamBo paramBo) {
        BasePageData pageData = new BasePageData();
        PageHelper.startPage(paramBo.getPage(), paramBo.getLimit());
        TopicExample topicExample = new TopicExample();
        topicExample.setOrderByClause(paramBo.getSort() + " " + paramBo.getOrder());
        TopicExample.Criteria criteria = topicExample.createCriteria();
        if (title != null && !"".equals(title)) {
            criteria.andTitleLike("%" + title + "%");
        }
        if (subtitle != null && !"".equals(subtitle)) {
            criteria.andSubtitleLike("%" + subtitle + "%");
        }
        criteria.andDeletedEqualTo(false);
        List<Topic> topics = topicMapper.selectByExampleWithBLOBs(topicExample);
        List<TopicVo> topicVos = new ArrayList<>();
        for (Topic topic : topics) {
            TopicVo topicVo = TransUtils.topic2topicVo(topic);
            topicVos.add(topicVo);
        }
        PageInfo<Topic> pageInfo = new PageInfo<>(topics);

        int total = pageInfo.getSize();
        pageData.setTotal(total);
        pageData.setList(topicVos);
        pageData.setPage(pageInfo.getPageNum());
        pageData.setLimit(pageInfo.getPageSize());
        pageData.setPages(pageInfo.getPages());
        return pageData;
    }

    @Override
    public void deleteTopic(TopicBo topicBo) {
        Topic topic = TransUtils.topicBo2topic(topicBo);
        topic.setDeleted(true);
        topicMapper.updateByPrimaryKeyWithBLOBs(topic);
    }

    @Override
    public TopicVo updateTopic(TopicBo topicBo) {
        Topic topic = topicMapper.selectByPrimaryKey(topicBo.getId());
        //判断是否修改
        if (topic.getTitle().equals(topicBo.getTitle()) &&
                topic.getSubtitle().equals(topicBo.getSubtitle()) &&
                topic.getPrice().compareTo(topicBo.getPrice()) == 0 &&
                topic.getReadCount().equals(topicBo.getReadCount()) &&
                topic.getPicUrl().equals(topicBo.getPicUrl()) &&
                topic.getContent().equals(topicBo.getContent())) {
            return null;
        }
        Topic topic1 = TransUtils.topicBo2topic(topicBo);
        Date now = new Date(System.currentTimeMillis());
        topic1.setUpdateTime(now);
        topic1.setDeleted(false);
        topicMapper.updateByPrimaryKeyWithBLOBs(topic1);
        TopicVo topicVo = TransUtils.topic2topicVo(topic1);
        return topicVo;
    }

    @Override
    public TopicVo createTopic(TopicBo topicBo) {
        Topic topic = TransUtils.topicBo2topic(topicBo);
        Date now = new Date(System.currentTimeMillis());
        topic.setAddTime(now);
        topic.setUpdateTime(now);
        topic.setDeleted(false);
        topic.setSortOrder(1);
        topicMapper.insert(topic);
        TopicVo topicVo = TransUtils.topic2topicVo(topic);
        return topicVo;
    }

    //有bug尚未解决，先提交
    //bug已修复
    @Override
    public CouponVo updateCoupon(UpdateCouponBo updateCouponBo) {
        Coupon coupon = couponMapper.selectByPrimaryKey(updateCouponBo.getId());
        //判断是否需要修改
        if(coupon.getName().equals(updateCouponBo.getName()) &&
           coupon.getDesc().equals(updateCouponBo.getDesc()) &&
                coupon.getTag().equals(updateCouponBo.getTag()) &&
                coupon.getTotal().equals(updateCouponBo.getTotal()) &&
                (coupon.getDiscount().compareTo(updateCouponBo.getDiscount())) == 0 &&
                (coupon.getMin().compareTo(updateCouponBo.getMin())) == 0 &&
                coupon.getLimit().equals(updateCouponBo.getLimit()) &&
                coupon.getType().equals(updateCouponBo.getType()) &&
                coupon.getStatus().equals(updateCouponBo.getStatus()) &&
                coupon.getGoodsType().equals(updateCouponBo.getGoodsType()) &&
                coupon.getTimeType().equals(updateCouponBo.getTimeType())){
            if(coupon.getDays() == null || "".equals(coupon.getDays())){
                if(coupon.getStartTime().equals(updateCouponBo.getStartTime()) && coupon.getEndTime().equals(updateCouponBo.getEndTime())){
                    return null;
                }
            }
            if(coupon.getStartTime() == null && coupon.getEndTime() == null){
                if(coupon.getDays().equals(updateCouponBo.getDays())){
                    return null;
                }
            }
        }
        Coupon coupon1 = TransUtils.CouponBoTOCoupon(updateCouponBo,couponMapper);
        Date now = new Date(System.currentTimeMillis());
        coupon1.setUpdateTime(now);
        coupon1.setAddTime(now);
        couponMapper.updateByPrimaryKeySelective(coupon1);
        CouponVo couponVo = TransUtils.CouponToCouponVo(coupon1);
        return couponVo;
    }

    @Override
    public AdItems addAd(AdBo adBo) {
        //判断是否包含违禁词
        AdItems adItems1 = isIllegal(adBo);
        if(adItems1 != null){
            return adItems1;
        }
        Ad ad = TransUtils.Bo2Ad(adBo);
        ad.setDeleted(false);
        Date now = new Date(System.currentTimeMillis());
        ad.setAddTime(now);
        ad.setUpdateTime(now);
        adMapper.insertSelective(ad);
        AdItems adItems = TransUtils.Ad2Vo(ad);
        return adItems;
    }

    private AdItems isIllegal(AdBo adBo) {
        List<String> words = ban.getWords();
        for(String word : words){
            if(adBo.getContent().contains(word) || adBo.getName().contains(word)){
                AdItems adItems = new AdItems();
                adItems.setContent("包含违禁词");
                return adItems;
            }
        }
        return null;
    }

    @Override
    public AdItems updateAd(AdBo adBo) {
        Ad ad = adMapper.selectByPrimaryKey(adBo.getId());
        //判断是否修改
        if(ad.getName().equals(adBo.getName()) &&
            ad.getContent().equals(adBo.getContent()) &&
            ad.getLink().equals(adBo.getLink()) &&
            ad.getPosition().equals(adBo.getPosition()) &&
            ad.getEnabled().equals(adBo.getEnabled()) &&
            ad.getUrl().equals(adBo.getUrl())){
            return null;
        }
        //判断是否包含违禁词
        AdItems adItems1 = isIllegal(adBo);
        if(adItems1 != null){
            return adItems1;
        }
        Ad ad1 = TransUtils.Bo2Ad(adBo);
        Date now = new Date(System.currentTimeMillis());
        ad1.setUpdateTime(now);
        ad1.setDeleted(false);
        adMapper.updateByPrimaryKey(ad1);
        AdItems adItems = TransUtils.Ad2Vo(ad1);
        return adItems;
    }

    @Override
    public TopicReadVo readTopic(Integer id) {
        TopicReadVo topicReadVo = new TopicReadVo();
        Topic topic = topicMapper.selectByPrimaryKey(id);
        int length = topic.getGoods().length;
        List<Goods> goodsList = new ArrayList<>();
        int i = 0;
        //得到goodsId的数组
        String[] goodsIds = topic.getGoods();
        //遍历id数组，逐个查询goods，存入goodsList
        for(i = 0;i < length;i++){
            Goods goods = goodsMapper.selectByPrimaryKey(Integer.parseInt(goodsIds[i]));
            goodsList.add(goods);
        }
        topicReadVo.setTopic(TransUtils.topic2topicVo(topic));
        topicReadVo.setGoodsList(goodsList);
        return topicReadVo;
    }

    @Override
    public CouponVo addCoupon(AddCouponBo addCouponBo) {
        if ((addCouponBo.getEndTime() == null || addCouponBo.getStartTime() == null) && ("".equals(addCouponBo.getDays()) || addCouponBo.getDays() == null)) {
            return null;
        }
        if(addCouponBo.getEndTime() == null || addCouponBo.getStartTime() == null){
            if(addCouponBo.getDays() < 0 || "".equals(addCouponBo.getDays()) || addCouponBo.getDays() == null){
                return null;
            }
        }
        Coupon coupon1 = TransUtils.CouponBoToCoupon(addCouponBo,couponMapper);
        Date now = new Date(System.currentTimeMillis());
        coupon1.setAddTime(now);
        coupon1.setUpdateTime(now);
        coupon1.setDeleted(false);
        couponMapper.insertSelective(coupon1);
        CouponVo couponVo = TransUtils.CouponToCouponVo(coupon1);
        return couponVo;
    }

    @Override
    public void batchDelete(BatchDeleteBo batchDeleteBo) {
        Integer[] ids = batchDeleteBo.getIds();
        int length = ids.length;
        int i = 0;
        for(i = 0;i < length;i++){
            Topic topic = topicMapper.selectByPrimaryKey(ids[i]);
            topic.setDeleted(true);
            topicMapper.updateByPrimaryKey(topic);
        }
    }

    @Override
    public BasePageData<WxCouponMyListVo> getMyList(int status, BaseParam baseParam) {
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria myListCriteria = couponExample.createCriteria();
        // 设置分页
        PageHelper.startPage(baseParam.getPage(),baseParam.getLimit());

        myListCriteria.andStatusEqualTo((short) status);

        //查询
        List<Coupon> couponList = couponMapper.selectByExample(couponExample);
        List<WxCouponMyListVo> wxCouponMyListVos = new ArrayList<>();
        Date date = new Date();
        for (Coupon coupon : couponList) {
            WxCouponMyListVo wxCouponMyListVo = new WxCouponMyListVo(coupon.getId(),coupon.getGoodsType(),coupon.getName(),
                    coupon.getDesc(),coupon.getTag(),coupon.getMin(),coupon.getDiscount(),
                    date,date,true);
            wxCouponMyListVos.add(wxCouponMyListVo);
        }
        return BasePageData.ok(wxCouponMyListVos);
    }


    @Override
    public List<Ad> getAllEnableAds() {
        AdExample adExample = new AdExample();
        AdExample.Criteria adExampleCriteria = adExample.createCriteria();
        // 获取已启动的广告
        adExampleCriteria.andEnabledEqualTo(true);
        List<Ad> adList = adMapper.selectByExample(adExample);
        return LimitListSizeUtil.limitSize(adList);
    }
}
